<template>
  <div :class="$style.main">
    <div :class="$style.content">
      <search-area>
        <template v-slot:1_1>
          <el-form-item label="报警规则名称">
            <el-input v-model="title"></el-input>
          </el-form-item>
        </template>
        <template v-slot:1_2>
          <el-form-item label="报警级别">
            <el-select filterable placeholder="请选择" v-model="selected">
              <el-option
                :key="item.value"
                :label="item.label"
                :value="item.value"
                v-for="item in options">
              </el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-slot:1_3>
          <el-form-item label=" ">
            <el-button-group>
              <el-button type="primary" v-on:click="search">查询</el-button>
              <el-button v-on:click="goClear">清除</el-button>
            </el-button-group>
          </el-form-item>
        </template>
      </search-area>
      <div style="margin-top:10px">
        <el-button-group>
          <el-button size="mini" type="primary">全局报警规则</el-button>
          <el-button size="mini" type="primary">局部报警规则</el-button>
          <el-button size="mini" type="primary" v-on:click="openRules">启用规则</el-button>
          <el-button size="mini" type="primary" v-on:click="stopRules">停用规则</el-button>
          <el-button size="mini" type="primary">批量上传</el-button>
          <el-button size="mini" type="primary">下载规则模版</el-button>
          <el-button size="mini" type="primary">导出设备数据项</el-button>
          <el-button size="mini" type="primary">阈值规则</el-button>
        </el-button-group>
      </div>
      <div style="margin-top:10px">
        <el-table
          :cell-style="tableCellStyle"
          :data="tableData"
          :header-cell-style="headerCellStyle"
          @selection-change="handleSelectionChange"
          ref="multipleTable"
          style="width: 100%;"
          tooltip-effect="dark"
        >
          <el-table-column
            type="selection"
            width="42">
          </el-table-column>
          <el-table-column
            label="报警规则名称"
            prop="title"
            show-overflow-tooltip
            width="100">
          </el-table-column>
          <el-table-column
            :formatter="alertTypeFormatter"
            label="规则类别"
            prop="nodeIds"
            show-overflow-tooltip
            width="80">
          </el-table-column>
          <el-table-column
            label="资源编码"
            prop="deviceSn"
            show-overflow-tooltip
            width="80">
          </el-table-column>
          <el-table-column
            label="资源名称"
            prop="deviceName"
            show-overflow-tooltip
            width="80">
          </el-table-column>
          <el-table-column
            :formatter="severityFormatter"
            label="报警级别"
            prop="severity"
            show-overflow-tooltip
            width="80">
          </el-table-column>
          <el-table-column
            :formatter="enabledFormatter"
            label="是否启用"
            prop="enabled"
            show-overflow-tooltip
            width="80">
          </el-table-column>
          <el-table-column
            :formatter="updateTimeFormatter"
            label="更新时间"
            prop="updateTime"
            show-overflow-tooltip
            width="80">
          </el-table-column>
          <el-table-column
            label="报警消息"
            prop="message"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button-group>
                <el-button @click="startUse(scope.$index, scope.row)" size="mini" type="success" v-show="!showDom(scope.row)">
                  启用
                </el-button>
                <el-button @click="stopUse(scope.$index, scope.row)" size="mini" type="danger" v-show="showDom(scope.row)">
                  停用
                </el-button>
                <el-button @click="handleEdit(scope.$index, scope.row)" size="mini" type="primary">编辑</el-button>
                <el-button @click="handleDelete(scope.$index, scope.row)" size="mini" type="danger">删除</el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div :class="$style.pagination">
        <el-pagination
          :current-page="currentPage"
          :page-size="10"
          :page-sizes="[10, 20, 50, 100, 99999]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          background
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
      <div>
        <AlertRuleEdilt :EdlitData="EdlitData" :Visible="Visible" @hideVisible="hideVisible"></AlertRuleEdilt>
      </div>
    </div>
  </div>
</template>
<script>
import api from './../../../common/js/api';
import { mapState } from 'vuex';
import AlertRuleEdilt from './../../../default/components/alert-rule/AlertRuleEdilt.vue';
import SearchArea from './../../../default/components/search-area/SearchArea.vue';

export default {
  components: {
    AlertRuleEdilt,
    SearchArea
  },
  data () {
    return {
      title: '',
      selected: '',
      damain: '',
      styleObj: {
        // background: '#f00'
      },
      options: [{
        value: '1',
        label: '正常'
      }, {
        value: '2',
        label: '注意'
      }, {
        value: '3',
        label: '警告'
      }, {
        value: '4',
        label: '危险'
      }],
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pagesize: 10,
      total: 0,
      selectTableData: [],
      guize: '',
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '120px',
      EdlitData: {},
      Visible: false
    };
  },
  mounted () {
    api.post('resourceUIService.getResourceById', this.currentResourceId).then(res => {
      if (res.code == 0) {
        this.damain = res.data.domainPath;
        this.search();
      }
    });
  },
  methods: {
    handleSelectionChange: function (val) {
      console.log(val);
      this.selectTableData = val;
    },
    showDom: function (data) {
      if (data.enabled) {
        return true;
      } else {
        return false;
      }
    },
    openRules: function () {
      this.guize = true;
      var len = 0;
      for (var index in this.selectTableData) {
        if (this.selectTableData[index].enabled == false) {
          len = len + 1;
        }
      }
      this.$confirm('当前选中' + len + '条规则处于停用状态,确定要启用吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this;
        var pramer = [];
        var selectId = [];
        for (let index in _this.selectTableData) {
          selectId.push(_this.selectTableData[index].id);
        }
        pramer.push(selectId);
        pramer.push(_this.guize);
        api.post('resourceUIService.enabledKpiThresholds', pramer).then(res => {
          if (_this.guize == true) {
            var failNum = len - res.data.successObj.length;
            this.$message({
              type: 'success',
              message: '启用成功规则数量' + res.data.successObj.length + '，启用失败规则数量' + failNum
            });
          } else {
            failNum = len - res.data.successObj.length;
            this.$message({
              type: 'success',
              message: '停用成功规则数量' + res.data.successObj.length + '，停用失败规则数量' + failNum
            });
          }
          this.search();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消启用'
        });
      });
    },
    stopRules: function () {
      this.guize = false;
      var len = 0;
      for (var index in this.selectTableData) {
        if (this.selectTableData[index].enabled == true) {
          len = len + 1;
        }
      }
      this.$confirm('当前选中' + len + '条规则处于启用状态,确定要停用吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this;
        var pramer = [];
        var selectId = [];
        for (let index in _this.selectTableData) {
          selectId.push(_this.selectTableData[index].id);
        }
        pramer.push(selectId);
        pramer.push(_this.guize);
        api.post('resourceUIService.enabledKpiThresholds', pramer).then(res => {
          var failNum = len - res.data.successObj.length;
          this.$message({
            type: 'success',
            message: '停用成功规则数量' + res.data.successObj.length + '，停用失败规则数量' + failNum
          });
          this.search();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消停用'
        });
      });
    },
    dateFormat (fmt, date) {
      let ret;
      const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString() // 秒
      };
      for (let k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt);
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')));
        }
        ;
      }
      ;
      return fmt;
    },
    updateTimeFormatter: function (row, column) {
      let date = new Date(row.updateTime);
      return this.dateFormat('YYYY-mm-dd HH:MM:SS', date);
    },
    enabledFormatter: function (row, column) {
      let enabled = row.enabled;
      return enabled ? '已启用' : '已停用';
    },
    alertTypeFormatter: function (row, column) {
      let nodeIds = row.nodeIds;
      return nodeIds ? '局部规则' : '全局规则';
    },
    severityFormatter: function (row, column) {
      let severity = row.severity;
      if (severity == 1) {
        return '正常';
      } else if (severity == 2) {
        return '注意';
      } else if (severity == 3) {
        return '警告';
      } else if (severity == 4) {
        return '危险';
      }
    },
    handleSizeChange: function (val) {
      this.pagesize = val;
      this.search();
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage;
      this.search();
    },
    headerCellStyle () {
      return 'border: none;color: #9ac9ea';
    },
    tableCellStyle () {
      return 'border: none;color:#bbb';
    },
    search: function () {
      var params = [
        { 'domain': this.damain },
        {
          'start': this.currentPage,
          'length': this.pagesize,
          'statCount': true,
          'sort': 'createTime',
          'sortType': 'DESC'
        }
      ];
      api.post('resourceUIService.getKpiThresholdListByConditionWithPage', params).then(res => {
        if (res.code == 0) {
          this.tableData = res.data.data;
          this.total = res.data.total;
        }
      });
    },
    goClear: function () {
      this.title = '';
      this.severity = null;
    },
    stopUse (index, row) {
      var pramer = [];
      var selectId = [];
      selectId.push(row.id);
      pramer.push(selectId);
      pramer.push('false');
      api
        .post('resourceUIService.enabledKpiThresholds', pramer)
        .then(ret => {
          this.$message({
            type: 'success',
            message: '停用成功'
          });
          this.search();
        });
    },
    startUse (index, row) {
      var pramer = [];
      var selectId = [];
      selectId.push(row.id);
      pramer.push(selectId);
      pramer.push('true');
      api
        .post('resourceUIService.enabledKpiThresholds', pramer)
        .then(ret => {
          this.$message({
            type: 'success',
            message: '启用成功'
          });
          this.search();
        });
    },
    handleEdit: function (index, row) {
      this.Visible = true;
      row.EdlitTitle = '编辑' + (row.nodeIds ? '局部' : '全局') + '报警规则';
      row.severity = this.severityFormatter(row);
      this.EdlitData = row;
    },
    hideVisible: function (data) {
      this.Visible = data;
    },
    handleDelete (index, row) {
      if (row.enabled) {
        this.$message({
          type: 'warning',
          message: '该告警规则启用中，无法删除！'
        });
      } else {
        api.post('resourceUIService.deleteKpiThresholds', [[row.id]]).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功！'
          });
          this.search();
        });
      }
    }
  },
  computed: {
    ...mapState('resource', [
      'devices',
      'domains',
      'currentResourceId'
    ])
  },
  watch: {}
};
</script>
<style lang="scss" module>
@import "./../../../style/default/alert-rule.scss";

</style>
